package com.atguigu.crowd.mvc.config;

import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.service.api.AuthService;
import com.atguigu.crowd.service.api.RoleService;
import crowd.entity.Admin;
import crowd.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AuthService authService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据username查询admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);

        // 根据admin的id查询角色信息
        List<Role> assignedRole = roleService.getAssignedRole(admin.getId());

        // 根据admin的id查询权限信息
        List<String> assginedAuthNameByAdminId = authService.getAssginedAuthNameByAdminId(admin.getId());

        // 创建集合用来存储GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (Role role : assignedRole) {

            // 给角色添加前缀
            String roleName = "ROLE_" + role.getName();

            // 将角色信息添加至GrantedAuthority
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }

        // 将权限信息添加至GrantedAuthority集合中
        for (String authName : assginedAuthNameByAdminId) {

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);

        }

        // 封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);

        return securityAdmin;

    }

}
